
import csv
def load_data(filename):
    """加载CSV文件数据"""
    data = []
    encodings = ['gb18030', 'utf-8', 'gbk', 'big5']  # 中文常用编码

    for encoding in encodings:
        try:
            with open(filename, mode='r', encoding=encoding) as file:
                reader = csv.reader(file)
                headers = next(reader)
                for row in reader:
                    data.append(row)
                print(f"成功用 {encoding} 编码读取文件")
                return headers, data
        except UnicodeDecodeError:
            continue

    raise ValueError(f"无法解码文件，尝试过的编码：{encodings}")


def search_consumption(headers, data):
    """查询消费数据"""
    print("\n可查询的省份有：")
    provinces = [row[0] for row in data]
    print(", ".join(provinces))

    print("\n可查询的项目有：")
    print(", ".join(headers[1:]))

    while True:
        print("\n" + "=" * 40)
        province = input("请输入要查询的省份（输入q退出）：").strip()
        if province.lower() == 'q':
            break

        if province not in provinces:
            print("错误：省份不存在，请重新输入！")
            continue

        print("\n请选择要查询的项目（可多选，用逗号分隔）：")
        for i, item in enumerate(headers[1:], 1):
            print(f"{i}. {item}")

        selections = input("请输入项目编号（如1,3,5）：").strip()
        try:
            selected_indices = [int(s.strip()) for s in selections.split(',')]
            selected_items = [headers[i] for i in selected_indices]
        except (ValueError, IndexError):
            print("错误：输入格式不正确，请重新输入！")
            continue

        # 查找数据
        result = next(row for row in data if row[0] == province)

        print("\n查询结果：")
        print(f"省份：{province}")
        for item in selected_items:
            value = result[headers.index(item)]
            print(f"{item}：{value}")


def main():
    try:
        headers, data = load_data(r"C:\Users\86178\Desktop\xiaofei.csv")
        search_consumption(headers, data)
    except FileNotFoundError:
        print("错误：未找到xiaofei.csv文件，请确保文件存在！")
    except Exception as e:
        print(f"发生错误：{e}")

if __name__ == "__main__":
    try:
        headers, data = load_data(r"C:\Users\86178\Desktop\xiaofei.csv")
        search_consumption(headers, data)
    except FileNotFoundError:
        print("错误：未找到xiaofei.csv文件，请确保文件存在！")
    except Exception as e:
        print(f"发生错误：{e}")